package com.gonsin.gview.logic.utils;

import com.gonsin.gview.logic.services.GViewClientServiceImpl;
import com.gonsin.gview.logic.services.GViewDataServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;

import static com.gonsin.gview.logic.config.GViewFileProperties.TEMP_PATH;

/**
 * GView的工具类
 */
public class GViewUtils {


    private static GViewDataServiceImpl dataService = null;
    private static GViewClientServiceImpl clientService = null;

    /**
     * 通知数据变更
     */
    public static void notifyDataChanged(String edificeKey, String source) {
        if(dataService == null){
            dataService = SpringUtil.getBean(GViewDataServiceImpl.class);
        }

        if(StringUtils.isEmpty(edificeKey)){
            return;
        }
        dataService.notifyDataSourceChanged(edificeKey, source);
    }

    /**
     * 通知数据变更
     */
    public static void notifyDataChangedByDataId(String edificeKey, String dataId) {
        if(clientService == null){
            clientService = SpringUtil.getBean(GViewClientServiceImpl.class);
        }

        if(StringUtils.isEmpty(edificeKey)){
            return;
        }
        clientService.notifyDataChanged(edificeKey, dataId);
    }


    /**
     * 通过viewName生成url
     */
    public static String gview(String viewName){
        return "view?viewName=" + viewName;
    }


    /**
     * 获取当前请求的Session
     * @return
     */
    public static HttpSession getSession(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes == null){
            return null;
        }
        return attributes.getRequest().getSession();
    }


    /**
     * 获取当前请求的 Request
     * @return
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes == null){
            return null;
        }
        return attributes.getRequest();
    }


    /**
     * 获取当前请求的 Response
     * @return
     */
    public static HttpServletResponse getResponse(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes == null){
            return null;
        }
        return attributes.getResponse();
    }


    /**
     * 如果文件时通过gview上传的，该方法是将url转为本地路径
     */
    public static String getPathFromUrl(String url){
        String tempPath = TEMP_PATH;
        if(url == null){
            return null;
        }
        String filename = url.substring(6);
        return tempPath + File.separator + filename;
    }
}
